import { defineStore } from 'pinia'
import { getUserInfo, loginByCode, loginByPassword } from '@/api/user'
import { setToken, clearToken, getToken } from '@/utils/auth'
const useAppStore = defineStore('user', {
  state: () => ({
    userInfo: {},
    token: getToken()
  }),
  getters: {
    role(state) {
      return state?.userInfo?.role?.name || ''
    }
  },
  actions: {
    // Set user's information
    setInfo(partial) {
      // this.$patch(partial)
      this.userInfo = { ...this.userInfo, ...partial }
    },
    setGoldCoin(num) {
      this.userInfo.gold_coin += num
    },
    // Reset user's information
    resetInfo() {
      this.$reset()
    },

    // Get user's information
    async info() {
      const res = await getUserInfo()
      this.setInfo(res)
    },

    // Login
    async login(loginForm) {
      try {
        if (loginForm.code) {
          const res = await loginByCode(loginForm)
          this.token = res.token
          setToken(res.token)
        } else {
          const res = await loginByPassword(loginForm)
          this.token = res.token
          setToken(res.token)
        }
      } catch (err) {
        clearToken()
        throw err
      }
    },
    logoutCallBack() {
      // const appStore = useAppStore()
      clearToken()
      this.resetInfo()
      // removeRouteListener()
      // appStore.clearServerMenu()
    },
    // Logout
    async logout() {
      try {
        // await userLogout();
      } finally {
        this.logoutCallBack()
      }
    }
  }
})

export default useAppStore
